using System;
using System.Globalization;

namespace OSDK
{
    public class WeekHelper
    {
        public static int WeeksInYear(int year)
        {
            var cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
            return cal.GetWeekOfYear(new DateTime(year, 12, 28), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
        }

        public static int GetWeekNumberOfDate(DateTime today)
        {
            return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(today, CalendarWeekRule.FirstFourDayWeek,
                                                                     DayOfWeek.Monday);
        }

        public static DateTime FirstDateOfWeek(int year, int weekNum, CalendarWeekRule rule)
        {
            var jan1 = new DateTime(year, 1, 1);

            int daysOffset = DayOfWeek.Monday - jan1.DayOfWeek;
            DateTime firstMonday = jan1.AddDays(daysOffset);


            Calendar cal = CultureInfo.CurrentCulture.Calendar;
            int firstWeek = cal.GetWeekOfYear(jan1, rule, DayOfWeek.Monday);

            if (firstWeek <= 1)
            {
                weekNum -= 1;
            }

            DateTime result = firstMonday.AddDays(weekNum*7);

            return result;
        }

        public static DateTime First(int year, int week, DayOfWeek dayOfWeek)
        {

            var jan1 = new DateTime(year, 1, 1);

            return jan1.AddDays((week - 1) * 7 + dayOfWeek - jan1.DayOfWeek);

        }

        public static DateTime GetDateFromWeek(int year, int week)
        {
            GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench);
            DateTime d = new DateTime(year, 12, 31);
            int weeksInYear = calendar.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
            int weeksToSubtract = weeksInYear - week;
            d = calendar.AddWeeks(d, -weeksToSubtract);
            d = d.AddDays(1 - (int)d.DayOfWeek);
            return d;
        }

    }
}